package eu.jk.data.dbcp;

import java.sql.Connection;
import java.sql.DriverManager;



class Machine extends Thread{
	
	private PoolConfig config = null;
	
	private Pool pool = null;
	
	//需要创建的连接书目
	Integer amount = 0;
	
	//运行状态锁
	Boolean lock = false;
	
	public Machine(Pool pool) {
		super("ConnectionMachine");
		this.config = pool.getConfig();
		this.pool = pool;
		this.setDaemon(true);
		System.out.println(config.getPwd());
		//Load The Driver
		try {
			Class.forName(config.getDriverName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成新的连接
	 * 
	 * @return 一个连接
	 */
	private Connection generateConnection() {
		try {
			//Long start=new Date().getTime();
			Connection conn=DriverManager.getConnection(config.getDbURL(),
					config.getUser(),
					config.getPwd());
			//System.out.println((new Date().getTime()-start));
			return conn;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 设置状态更新锁。
	 * @return 成功设置锁 true，else false
	 */
	private boolean setLock(){
		if(lock)
			return false;
		synchronized(lock){
			if(lock)
				return false;
			lock=true;
		}
		return true;
	}
	
	/**
	 * 消除状态更新锁
	 */
	private void releaseLock(){
		synchronized(lock){
			lock=false;
		}
	}
	
	
	/**
	 * 设置连接数量,并且启动机器
	 * @param amount
	 * @return 设置是否成功
	 */
	public boolean runAmount(int amount){
		if(setLock()){
			this.amount=amount;
			synchronized(this){
				releaseLock();
				notify();
			}
			return true;
		}
		return false;
	}
	
	@Override
	/**
	 * 线程部分,维护连接池中的连接个数
	 */
	public void run() {
		Connection conn=null;
		while (true) {
			setLock();
			while(amount>0){
				conn=generateConnection();
				if(conn!=null){
					pool.putConnection(conn);
					amount--;
				}
			}
			releaseLock();
			synchronized(this){
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
